clear all
global system "linux"

if "${system}" == "linux" {
	*global code "/"
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"


*** 0. Create data for simul
clear
set obs `=100/2.5 + 1'
gen diff = -50 + 2.5* (_n-1)

expand 2 if _n == _N, g(fake)
replace diff = .1 if fake==1
drop fake
sort diff

gen lowbal = diff <=0 
gen simul = 1
save "${temp}/crism-simul-sample.dta", replace

**** 1. Create data

run "${code}/tba_elig/_crism-reg-data.do"

**** 2. Regression
cd "${code}/tba_elig"
local flist: dir "${Estimates}" files "*crism-*upto2012.ster"
foreach f of local flist {
	cap erase "${Estimates}/`f'"
}
local flist: dir "${log}" files "*"
foreach f of local flist {
	cap erase "${log}/`f'"
}

local cmd "sbatch -a 1-50 crism-refi.sh" 
di "`cmd'"

local JobIdFile "${log}/job-id.csv"  
log using `JobIdFile', name("jobid") text replace
shell `cmd'
log close _all

do _sbatch-job  "`JobIdFile'" 


**** 3. Create Figure for auto orig for those who refi'ed
foreach x in auto_orig auto_orig_amount auto_orig3 auto_orig3_amt {
	foreach If of numlist 1 2 {
		estimate use "${Estimates}/crism-`x'-spec4-If`If'-upto2012"
		run _plot_coeff_auto_orig
		graph export "${figure}/crism-`x'-spec4-If`If'-upto2012.pdf", replace
	}
}

**** 4. Create Table
run _esttab-latex-options.do
clear
set obs 1
gen lowbal = 1
gen diff = 1

label var lowbal "$1[z_{it}\leq 0]$"
label var diff "$ z_{it}$"


local vars "plainrefi5pct1 cashrefi5pct1"


foreach DepVar in `vars' {
	eststo clear
	foreach If of numlist 1/2 {
		foreach Poly of numlist 1/3 {
			estimate use "${Estimates}/crism-`DepVar'-spec`Poly'-If`If'-upto2012"
			eststo
			
			estadd local zip_ym "Y"
			estadd local control "Y"
		}
	}
	esttab using "${table}/crism-`DepVar'-upto2012.tex", replace keep(lowbal)  /// 
	 coeflabels(1.lowbal#c.diff "$ z_{it} \times 1[z_{it} \leq 0]$") ///
	 ${opts_esttab}  b(%9.4f) se(%9.4f) star(* 0.10 ** 0.05 *** 0.01) ///
	 stats(zip_ym control N r2_a, fmt(%1s %1s %9.0fc %9.3f) ///
	 labels("ZIPxMONTH FE" "Other Controls" "\midrule N. Obs." "Adj. $ R^2$")) ///
	 mtitle("Poly 1" "Poly 2" "Poly 3" "Poly 1" "Poly 2" "Poly 3") ///
	 mgroup("National CLL$\pm$\textdollar50K" "National CLL$\pm$\textdollar25K", pattern(1 0 0 1 0 0) ${opts_mgroups})
}

